package src

import (
	"fmt"
	"net/http"
	"encoding/json"
)

type CarsParam struct {
	CarNumbers []string `json:"vehicle_numbers"`
	Series string `json:"license_series"`
	License string `json:"license_number"`
}

func (c *CarsParam) fill(body []byte) {
	err := json.Unmarshal(body, c)
	if err!=nil {
		panic("unmarchalling CarsParam error")
	}
}

func transportHandler(w http.ResponseWriter, r *http.Request) {
	emp, body := ParseParams(r)
	var carsParam CarsParam
	carsParam.fill(body)

	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	
	var response Response
	if(len(carsParam.License)>0 || len(carsParam.CarNumbers)>0){	// fines list
		response = Response{ session, 0, "", getFines(3,1)} 
	} else {	//pay fine
		response = Response{ session, 0, "", getFineDetails()} 
	}
	obj,_ := json.Marshal(response)
	fmt.Fprint(w, string(obj))		
}

func getFines(unpaidNumber, paidNumber int) (fines []interface{}){
	params := make(map[string]string)
	params["link_id"] = "info_link"
	fines = append(fines,Appbutton{"appbutton","Информация","link","fines_info",[]map[string]string{params}})
	fines = append(fines, Separator{"separator","Неоплаченные","group"})
	for i :=0; i<unpaidNumber; i++ {
		fine :=getUnpaidFine()
		for _,fineElement :=range fine {
			fines = append(fines,fineElement)
		}
	}
	fines = append(fines, Separator{"separator","Оплаченные","group"})
	for i :=0; i<unpaidNumber; i++ {
		fine :=getPaidFine()
		for _,fineElement :=range fine {
			fines = append(fines,fineElement)
		}
	}	
	return
}

func getUnpaidFine() []interface{}{
	fine := make([]interface{},4)
	fine[0] = Separator{"separator","14.05.2013",""}
	fine[1] = Text{"text", "Номер постановления штрафа","1230345345345"}
	fine[2] = Text{"text","Сумма штрафа","800р"}
	fine[3] = Link{"link","Оплата","pay_link"}	
	
	return fine
}

func getPaidFine() []interface{}{
	fine := make([]interface{},4)
	fine[0] = Separator{"separator","12.01.2011",""}
	fine[1] = Text{"text", "Номер постановления штрафа","2340234012"}
	fine[2] = Text{"text","Сумма штрафа","300р"}
	fine[3] = Link{"link","Подробнее","paid_link"}	
	
	return fine
}

func getFineDetails() []interface{}{
	f := make([]interface{},9)
	f[0] = Title{"title","Штраф"}
	f[1] = Separator{"separator","Штраф от 29.11.2012",""}
	f[2] = Text{"text","Номер постановления","4289768562"}
	f[3] = Text{"text","Нарушитель", "Иванов Иван Петрович"}
	f[4] = Text{"text","Модель ТС","Wolsvagen Passat"}
	f[5] = Text{"text", "Гос. знак ТС", "A516BB197"}
	f[6] = Text{"text","Сумма штрафа","3200 руб."}
	f[7] = Text{"text","Место нарушения","???"}
	bp :=ButtonParams{"M000944289768562ZZZ1","Оплатить","Отмена","Оплата штрафа происходит путём списания денежных средств (1000 руб.) со счёта вашего мобильного телефона. Произвести оплату?"}
	f[8] = Button{"button","Оплатить штраф от 09.01.2013","pay_fine", bp}
	
	return f
}
